package com.freesky.biz.icbc.service.impl;

import com.alibaba.fastjson.JSON;
import com.freesky.biz.icbc.config.LotteryRedisKeyManager;
import com.freesky.biz.icbc.domain.*;
import com.freesky.biz.icbc.mapper.LotteryMapper;
import com.freesky.biz.icbc.service.ILotteryService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.core.redis.RedisCache;
import com.freesky.common.enums.ExportStatusEnum;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.system.domain.TExportRecord;
import com.freesky.system.service.ITExportRecordService;
import com.freesky.system.task.SyncReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class LotteryServiceImpl implements ILotteryService {

    private static final Logger logger = LoggerFactory.getLogger(LotteryServiceImpl.class);

    @Autowired
    private LotteryMapper lotteryMapper;

    @Autowired
    private ITExportRecordService exportRecordService;

    @Autowired
    private SyncReport syncReport;

    @Autowired
    private RedisCache redisCache;

    private static final int mulriple = 10000;

    @Override
    public List<TLotteryRecord> findList(TLotteryRecord lotteryRecord) {
        return lotteryMapper.findList(lotteryRecord);
    }

    @Override
    public AjaxResult exportFile(TLotteryRecord lotteryRecord) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        TExportRecord exportRecord = new TExportRecord();
        exportRecord.setId(SeqUtil.getSeqId());
        exportRecord.setBizType("LOTTERY_RECORD");
        exportRecord.setCreateBy(String.valueOf(sysUser.getUserId()));

        TExportRecord exportRecordSelect = exportRecordService.selectRecordExportByStatus(exportRecord);
        if (exportRecordSelect != null) {
            return AjaxResult.error("已经有下载任务");
        }

        exportRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());
        exportRecordService.insert(exportRecord);

        syncReport.exportFileMutilHeader(lotteryRecord, new TLotteryRecord(), ILotteryService.class,
                "findList", "抽奖活动",Long.parseLong(exportRecord.getId()),sysUser.getUserName());

        return AjaxResult.success();
    }

    @Override
    public List<TLotteryRecord618> find618List(TLotteryRecord618 entity) {
        return lotteryMapper.find618List(entity);
    }

    @Override
    public AjaxResult export618File(TLotteryRecord618 entity) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        TExportRecord exportRecord = new TExportRecord();
        exportRecord.setId(SeqUtil.getSeqId());
        exportRecord.setBizType("LOTTERY_618_RECORD");
        exportRecord.setCreateBy(String.valueOf(sysUser.getUserId()));

        TExportRecord exportRecordSelect = exportRecordService.selectRecordExportByStatus(exportRecord);
        if (exportRecordSelect != null) {
            return AjaxResult.error("已经有下载任务");
        }

        exportRecord.setStatus(ExportStatusEnum.SUBMIT_WAIT.getValue());
        exportRecordService.insert(exportRecord);

        syncReport.exportFileMutilHeader(entity, new TLotteryRecord618(), ILotteryService.class,
                "find618List", "618抽奖活动",Long.parseLong(exportRecord.getId()),sysUser.getUserName());

        return AjaxResult.success();
    }


    @Override
    public void lotteryInit(){
        LotteryModel lotteryModel = new LotteryModel();
        lotteryModel.setState(1);
        List<LotteryModel> lotteryModelList = lotteryMapper.selectLotteryList(lotteryModel);

        for(LotteryModel lotteryDataModel:lotteryModelList){
            Integer lotteryId = Integer.valueOf(lotteryDataModel.getId());
            Boolean result = redisCache.redisTemplate.opsForValue().setIfAbsent(
                    LotteryRedisKeyManager.getLotteryPrizeRedisKey(lotteryId), "1");

            //已经初始化到缓存中了，不需要再次缓存
            if (!result) {
                logger.info("【lottery:"+lotteryId+"】已经加载过!");
                continue;
            }
            //缓存KEY
            setLotteryToRedis(LotteryRedisKeyManager.getLotteryRedisKey(lotteryId),lotteryDataModel);

            //取奖品信息
            List<LotteryItemModel> lotteryItems = getLotteryItemByLotteryId(lotteryDataModel.getId());
            LotteryItemModel defaultLotteryItem = lotteryItems.parallelStream().filter(o -> o.getDefaultItem().intValue() == 1).findFirst().orElse(null);

            //Map<String, Object> lotteryItemMap = new HashMap<>(16);
            redisCache.setCacheObject(LotteryRedisKeyManager.getLotteryItemRedisKey(lotteryId), JSON.toJSONString(lotteryItems));
            redisCache.setCacheObject(LotteryRedisKeyManager.getDefaultLotteryItemRedisKey(lotteryId), JSON.toJSONString(defaultLotteryItem));

            //lotteryItemMap.put(LotteryRedisKeyManager.getLotteryItemRedisKey(lotteryId), lotteryItems);
            //lotteryItemMap.put(LotteryRedisKeyManager.getDefaultLotteryItemRedisKey(lotteryId), defaultLotteryItem);
            //redisCache.multiSet(lotteryItemMap);

            List<LotteryPrizeModel> lotteryPrizes = getLotteryPrizeByLotteryId(lotteryDataModel.getId());

            //保存一个默认奖项
            AtomicReference<LotteryPrizeModel> defaultPrize = new AtomicReference<>();
            lotteryPrizes.stream().forEach(lotteryPrize -> {
                if (lotteryPrize.getId().equals(defaultLotteryItem.getPrizeId())) {
                    defaultPrize.set(lotteryPrize);
                }
                String key = LotteryRedisKeyManager.getLotteryPrizeRedisKey(lotteryId, lotteryPrize.getId());
                setLotteryPrizeToRedis(key, lotteryPrize);
            });

            String key = LotteryRedisKeyManager.getDefaultLotteryPrizeRedisKey(lotteryId);
            redisCache.setCacheObject(key,defaultLotteryItem.getPrizeId());
            //setLotteryPrizeToRedis(key, defaultPrize.get());
        }
    }

    @Override
    public List<LotteryModel> selectLotteryList(LotteryModel lotteryModel) {
        return lotteryMapper.selectLotteryList(lotteryModel);
    }

    @Override
    public int resetLotteryById(String lotteryId) {
        return lotteryMapper.resetLotteryById(lotteryId);
    }

    @Override
    public List<LotteryItemModel> getLotteryItemByLotteryId(String lotteryId) {
        return lotteryMapper.getLotteryItemByLotteryId(lotteryId);
    }

    @Override
    public List<LotteryPrizeModel> getLotteryPrizeByLotteryId(String lotteryId) {
        return lotteryMapper.getLotteryPrizeByLotteryId(lotteryId);
    }

    private void setLotteryToRedis(String key, LotteryModel lotteryModel) {
        System.out.println("setLotteryToRedis,key:"+key);
        redisCache.hset(key, "id", lotteryModel.getId());
        redisCache.hset(key, "state", lotteryModel.getState());
        redisCache.hset(key, "algorithmType", lotteryModel.getAlgorithmType());
        redisCache.hset(key, "startTime", lotteryModel.getStartTime());
        redisCache.hset(key, "endTime", lotteryModel.getEndTime());
        redisCache.hset(key, "topic", lotteryModel.getTopic());
        redisCache.hset(key, "totalStock", lotteryModel.getTotalStock());
        redisCache.hset(key, "defaultPrizeId", lotteryModel.getDefaultPrizeId());
    }

    private void setLotteryPrizeToRedis(String key, LotteryPrizeModel lotteryPrize) {
        System.out.println("setLotteryPrizeToRedis,key:"+key);
        redisCache.hset(key, "id", lotteryPrize.getId());
        redisCache.hset(key, "lotteryId", lotteryPrize.getLotteryId());
        redisCache.hset(key, "prizeName", lotteryPrize.getPrizeName());
        redisCache.hset(key, "amt", lotteryPrize.getAmt());
        redisCache.hset(key, "prizeType", lotteryPrize.getPrizeType());
        redisCache.hset(key, "totalStock", lotteryPrize.getTotalStock());
        redisCache.hset(key, "validStock", lotteryPrize.getValidStock());
    }

}
